<template>
  <div class="productProNew">
    <div class="title"><h1><span>编辑</span></h1></div>
    <form name="newContent" class="basicInfor">

      <!--<div class="form-group required">-->
        <!--<label :for="'taskSn'+$attrs.text">任务编号：</label>-->
        <!--<input :disabled="true" autocomplete="off" type="text" class="form-control proName" :id="'taskSn'+$attrs.text" placeholder="请输入任务编号" required v-model="details.taskSn" />-->
      <!--</div>-->
      <div class="form-group required">
        <label :for="'taskName'+$attrs.text">线路名称：</label>
        <input autocomplete="off" type="text" class="form-control proName" :id="'taskName'+$attrs.text" placeholder="请输入线路名称" v-model="details.taskName" />
      </div>
      <h1 class="hide">出发日期（必填）</h1>
      <div class="form-group required">
        <label :for="'schduleDateStart'+$attrs.text">出发日期：</label>
        <input autocomplete="off" class="form-control ipt-datepicker adultPrice setoff" type="text" :id="'schduleDateStart'+$attrs.text" placeholder="起始时间" required v-model="details.startDate">
      </div>
      <h1 class="hide">游玩天数（必填）</h1>
      <div class="form-group required">
        <label :for="'strokeDay'+$attrs.text">游玩天数：</label>
        <input autocomplete="off" type="number" min="1" class="form-control adultPrice" :id="'strokeDay'+$attrs.text" placeholder="" required v-model="details.coDay">
      </div>
      <div class="form-group required">
        <label class="destxt" :for="'guideMobile'+$attrs.text">导游电话：</label>
        <input autocomplete="off" type="text" class="form-control proName" :id="'guideMobile'+$attrs.text" placeholder="请输入导游电话" required v-model="details.guideMobile" @blur="getPhone(details.guideMobile)"/>
      </div>
      <div class="form-group required">
        <label class="destxt" :for="'guideName'+$attrs.text">导游姓名：</label>
        <input autocomplete="off" type="text" class="form-control proName" :id="'guideName'+$attrs.text" placeholder="请输入导游姓名" required v-model="details.guideName" />
      </div>
      <h1 class="hide">出发地（必填）</h1>
      <div class="form-group departure">
        <label>出发地：</label>
        <Site v-on:DeparTure="deparTure"></Site>
      </div>
      <h1 class="hide">目的地（必填）</h1>
      <div class="form-group destination">
        <label>目的地：</label>
        <Site v-on:DeparTure="desTination"></Site>
      </div>

      <div class="form-group">
        <label>出团通知书附件：</label>
        <div class="Import MemberBtn">
          <input type="file" @change="noticeImport($event)" />
          <span>导入</span>
          <span class="g-tips import-tip">可导入excel、word、pdf文件或图片</span>
          <div class="files-container" v-if="tuanFileImg.length">
            <div class="file-imgs" v-for="(val, index) in tuanFileImg">
              <img :src="val.url ? val.url : val" alt="" />
              <span class="dele-img-icon" data-type="tuanImgFile" @click="deleFiles($event, val, index)">x</span>
            </div>
          </div>
          <div class="files-container">
            <div class="file-tags" v-for="(val, index) in showTuanFiles">
              <a :href="val.url" target="_blank">
                {{val.name ? val.name : '附件'+(index+1)}}
              </a>
              <span class="dele-file-icon" data-type="tuanfiles" @click="deleFiles($event, val, index)">x</span>
            </div>
          </div>
        </div>
      </div>

      <div class="form-group">
        <label>名单附件：</label>
        <div class="Import MemberBtn">
          <input type="file" @change="nameImport($event)" />
          <span>导入</span>
          <span class="g-tips import-tip">可导入excel、word、pdf文件或图片</span>
          <div class="files-container" v-if="rosterFileImg.length">
            <div class="file-imgs" v-for="(val, index) in rosterFileImg">
              <img :src="val.url ? val.url : val" alt="" />
              <span class="dele-img-icon" data-type="rosterImgFile" @click="deleFiles($event, val, index)">x</span>
            </div>
          </div>
          <div class="files-container">
            <div class="file-tags" v-for="(val, index, $event) in showRosterFiles">
              <a :href="val.url" target="_blank">
                {{val.name ? val.name : '附件'+(index+1)}}
              </a>
              <span class="dele-file-icon" data-type="rosterFiles" @click="deleFiles($event, val, index)">x</span>
            </div>
          </div>
        </div>
      </div>

      <div class="form-group">
        <label class="destxt" :for="'lxName'+$attrs.text">旅行社名称：</label>
        <input autocomplete="off" type="text" class="form-control proName" :id="'lxName'+$attrs.text" placeholder="请输入旅行社名称" required v-model="details.lxName" />
      </div>

      <!--<div class="form-group">-->
        <!--<label class="destxt" :for="'dispatchTime'+$attrs.text">派遣时间：</label>-->
        <!--<date-picker data-pickers field="dispatchTime"-->
                     <!--placeholder="请选择派遣时间"-->
                     <!--v-model="details.dispatchTime"-->
                     <!--format="yyyy/mm/dd"></date-picker>-->
      <!--</div>-->
      <!--<div class="form-group">-->
        <!--<label class="destxt" :for="'acceptTime'+$attrs.text">接受时间：</label>-->
        <!--<date-picker data-pickers field="acceptTime"-->
                     <!--placeholder="请选择接受时间"-->
                     <!--v-model="details.acceptTime"-->
                     <!--format="yyyy/mm/dd"></date-picker>-->
      <!--</div>-->
      <div class="form-group">
        <label class="destxt" :for="'remark'+$attrs.text">备注：</label>
        <textarea class="form-control proDes" :id="'remark'+$attrs.text" rows="6" placeholder="请输入备注信息" v-model="details.demo"></textarea>
      </div>

      <button type="button" class="btn btn-info confirmBtn" @click="submitPro()">提交</button>
    </form>
  </div>
</template>
<script>
    import Site from '@/components/public/site'
    import datepicker from 'vue-datepicker-simple/datepicker-2.vue'

    export default {
      data(){
        return{
          details: {},
          detailHttp: '',
          editHttp: '',
          deleFileHttp: '',
          showTuanUpload: true,
          showRosterFileUpload: true,
          rosterFiles: [],
          tuanFiles: [],
          showTuanFiles: [],
          tuanFileImg: [],
          uploadTuanFile: [],
          showRosterFiles: [],
          uploadRosterFile: [],
          rosterFileImg: [],
          deleTuanFileName: ''
        }
      },
      computed:{
        groupView(){//
          return this.$store.state.interface.groupView;
        },
        editGroup () {
          return this.$store.state.interface.addGroup;
        },
        deleFile () {
          return this.$store.state.interface.deleFile;
        },
        searchPhone(){
          return this.$store.state.interface.searchPhone
        }
      },
      components:{
        Site,
        'date-picker': datepicker
      },
      methods: {
        getPhone (phone) {
          let self = this;
          let isMobile = /^(13|14|15|17|18)\d{9}$/;
          if (!isMobile.test(phone)) {
            layer.msg('请填写有效手机号！');
            return false
          }
          let formData = new FormData();
          let isId = 1;
          formData.append('mobilePhone', phone);
          formData.append('isId', isId);
          self.$ajax.post(self.searchPhoneHttp, formData).then(function(res) {
            if (res.data.code === '10000') {
              let result = res.data.result;
              let id = result.customer.id || ''
              if (id) {
                self.details.guideName = result.customer.name || '';
                // self.guideradds.gender = result.customer.gender || '';
              }
            }
          })
        },
        // 出发
        deparTure: function(msg,path){
          this.details.startCity=msg;
          this.details.startPath=path;
        },
        // 目标
        desTination: function(msg,path){
          this.details.destiCity=msg;
          this.details.destiPath=path;
        },
        noticeImport (e) {
          let self = this;
          let file = e.target.files[0];
          console.log(file, 'eee')
          let reader = new FileReader();
          if(!/image\/\w+/.test(file.type)){
            self.showTuanFiles.push(file);
          } else {
            reader.onload = function(e){
              let result = e.target.result;
              if(self.tuanFileImg.indexOf(result) === -1){
                self.tuanFileImg.push(result);
              } else {
                layer.msg('图片已存在');
              }
            }
            reader.readAsDataURL(file);
            console.log(self.tuanFileImg)
          }
          self.uploadTuanFile.push(file);
        },
        nameImport (e) {
          let self = this;
          let file = e.target.files[0];
          let reader = new FileReader();
          if(!/image\/\w+/.test(file.type)){
            self.showRosterFiles.push(file);
          } else {
            reader.onload = function(e){
              let result = e.target.result;
              if(self.rosterFileImg.indexOf(result) === -1){
                self.rosterFileImg.push(result);
              } else {
                layer.msg('图片已存在');
              }
            }
            reader.readAsDataURL(file);
          }
          self.uploadRosterFile.push(file);
        },
        deleFiles (e, val, index) {
          let f_type = e.target.dataset.type;
          let self = this;
          layer.confirm('确定删除该附件？', {
            btn: ['确定','取消'] //按钮
          }, function(){
            // 需判断是本地的还是接口的
            // if (typeof val === 'string') {
            //
            // }
            let url = val.url;
            if (url) {
              let http_start = url.indexOf('http');
              if (http_start * 1 === 0) {
                let valArr = url.split('/');
                self.deleTuanFileName = valArr[valArr.length -1];
                let formData = new FormData();
                formData.append('id', val.id);
                formData.append('fileName', self.deleTuanFileName);
                self.$ajax.post(self.deleFileHttp, formData).then(function (res) {
                  let code = res.data.code;
                  if(code === '10000'){
                    self.details = {};
                    self.uploadRosterFile = [];
                    self.uploadTuanFile = [];
                    self.showTuanFiles = [];
                    self.showRosterFiles = [];
                    self.tuanFileImg = [];
                    self.rosterFileImg = [];
                    self.getDetail(self.$attrs.proid);
                  } else {
                    layer.msg('删除失败！');
                  }
                });
              } else {
                layer.msg('文件不存在！');
              }
            }

            // 本地图片
            if (typeof val === 'string' && f_type === 'tuanImgFile') {
              self.tuanFileImg.splice(index,1);
            }
            if (val.type && f_type === 'tuanfiles') {
              self.showTuanFiles.splice(index, 1);
              self.uploadTuanFile.splice(index - 1, 1);
            }

            if (typeof val === 'string' && f_type === 'rosterImgFile') {
              self.rosterFileImg.splice(index,1);
            }
            if (val.type && f_type === 'rosterFiles') {
              self.showRosterFiles.splice(index, 1);
              self.uploadRosterFile.splice(index - 1, 1);
            }
            $('.layui-layer-shade, .layui-layer').hide();
          }, function(){
            // 取消
          })
        },
        submitPro() { //提交判断是否信息完整

          let self = this;
          let isMobile = /^(13|14|15|17|18)\d{9}$/;

          // if (self.details.taskSn === '') {
          //   layer.msg('请填写任务编号！');
          //   return false
          // }

          if (self.details.guideName === '') {
            layer.msg('请填写导游姓名！');
            return false
          }
          if (!isMobile.test(self.details.guideMobile)) {
            layer.msg('请填写11位有效手机号');
            return false
          }
          if (self.details.taskName === '') {
            layer.msg('请填写线路名称！');
            return false
          }
          if (self.details.startDate === '') {
            layer.msg('请填写出发日期');
            return false
          }
          if (self.details.coDay === '') {
            layer.msg('请填写线路天数');
            return false
          }

          var formData = new FormData(); // 基础信息表单数据
          formData.append('id', self.details.id);
          // formData.append('taskSn', self.details.taskSn);
          formData.append('taskName', self.details.taskName);
          formData.append('guideName', self.details.guideName);
          formData.append('guideMobile', self.details.guideMobile);
          formData.append('lxName', self.details.lxName);
          // formData.append('dispatchTime', self.details.dispatchTime);
          // formData.append('acceptTime', self.details.acceptTime);
          formData.append('demo', self.details.demo);
          formData.append('coDay',self.details.coDay);
          formData.append('startDate',self.details.startDate);
          formData.append('startCity',self.details.startCity);
          formData.append('startPath',self.details.startPath);
          formData.append('destiCity',self.details.destiCity);
          formData.append('destiPath',self.details.destiPath);

          if (self.uploadRosterFile.length) {
            for (let item of self.uploadRosterFile) {
              formData.append('rosterFile[]', item);
            }
          }

          if (self.uploadTuanFile.length) {
            for (let item of self.uploadTuanFile) {
              formData.append('tuanFile[]', item);
            }
          }
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };
          self.$ajax.post(self.editHttp, formData, config).then(function (res) {
            let result = res.data.result || '';
            if (result.WbPaituan) {
              layer.msg('修改成功！');
            } else {
              layer.msg('修改失败！');
            }
          }, function (res) {
            layer.msg('修改失败！');
          });
        },
        getDetail (id) {
          let self = this;
          self.$ajax.post(self.detailHttp + '&id=' + id).then(function (res) {
            if (res.data.code === '10000') {
              self.details = res.data.result.WbPaituan;
              self.rosterFiles = self.details.rosterFiles;
              self.tuanFiles = self.details.tuanFiles;
              let image = /.(png|jpg)$/;
              // 显示图片
              if (self.rosterFiles) {
                for (let item of self.rosterFiles) {
                  if (image.test(item.url)) {
                    self.rosterFileImg.push(item);
                  } else {
                    self.showRosterFiles.push(item)
                  }
                }
              }
              if (self.tuanFiles) {
                for (let item of self.tuanFiles) {
                  if (image.test(item.url)) {
                    self.tuanFileImg.push(item);
                  } else {
                    self.showTuanFiles.push(item)
                  }
                }
              }
              let dispatchTime = self.details.dispatchTime;
              let acceptTime = self.details.acceptTime;
              if (dispatchTime) {
                let gtime = self.details.dispatchTime.trim().split(/\s+/)[0];
                self.details.dispatchTime = gtime;
              } else {
                self.details.dispatchTime = '未设置'
              }

              if (acceptTime) {
                let gtime = self.details.acceptTime.trim().split(/\s+/)[0];
                self.details.acceptTime = gtime;
              } else {
                self.details.acceptTime = '未设置';
              }

            } else {
              layer.msg('加载失败！');
            }
          }, function (res) {
            layer.msg('服务器错误！');
          })
        }
      },
      beforeMount() {
        let self = this;
        let editUrl = self.editGroup;
        let sessionId = JSON.parse(sessionStorage.getItem('customer')).sid;
        self.editHttp = editUrl + '?sid=' + sessionId;
        self.detailHttp = self.groupView + '?sid=' + sessionId;
        self.deleFileHttp = self.deleFile + '?sid=' + sessionId;
        self.getDetail(self.$attrs.proid);
      },
      mounted() {
        let self = this;
        $('.vue-datepicker input').height($('.form-group input').height());
        $('.vue-datepicker input').width($('.form-group input').width());
        $('#acceptTime').attr('disabled', true);
        $("#schduleDateStart"+self.$attrs.text).datepicker({
            showAnim: 'fadeIn',
            minDate: '-1y',
            maxDate: "+1y",
            defaultDate : +1,
            duration : 'fast',
            firstDay : 1 ,
            nextText : '下一月',
            prevText : '上一月',
            showButtonPanel: true,
            currentText : '今天',
            gotoCurrent : false,
            onSelect: function (dateText, inst){
              // self.start = Number(dateText.split('-').join(''));//将字符串转换为number
              //self.setoffDate = dateText;
              //self.details.startDate= Date.UTC(inst.currentYear, inst.currentMonth, inst.currentDay);
              self.details.startDate = dateText;
            },
        });
      }
    }
</script>
<style lang="scss" scoped>
    form{
        display:block;
    }
    .title{
        color:#4e5e7e;
    }
    .site{
        margin-left: 77px;
        margin-top: 0.325rem;
    }
    .form-control.like-textarea, .form-control.proDes, .form-group .mainImg{
      width: 70%;
    }
    .tuan-file{cursor: pointer;}
    .MemberBtn{
      background: none;
      color: #09ba79;
      font-size: 14px;
      padding-left: 22px;
      background-position: 0 center;
      background-repeat: no-repeat;
      margin: 0 10px;
    }
    .vue-datepicker{
      display: inline-block;
      background: #fff url(…DNJT/s4H4Eksi+pihmgTHw6f270WQ8atyocaPG0dc4gAADAALLNkNyjdPhAAAAAElFTkSuQmCC) no-repeat scroll right center;
      padding-right: 35px;
    }
    .NewMember{
      background-image:url('../../assets/images/search_xinjian_btn2.png');
    }
    .Import{
      display: inline-block;
      position: relative;
      border: none;
      height: 34px;
      padding: 0;
      cursor: pointer;
      background-image:url('../../assets/images/Import2.png');
      input{
        position: absolute;
        opacity: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
      }
      span{
        padding: 0 10px 0 22px;
        cursor: pointer;
        color: #09ba79;
        font-size: 14px;
        height: 34px;
        line-height: 34px;
      }
    }
    .deleteBtn{
      background-image:url('../../assets/images/modification2.png');
    }
    .modificationBtn{
      background-image:url('../../assets/images/delete2.png');
    }
    .import-tip.import-tip{margin-left: 105px;margin-top: 6px;padding-top: 6px;color: #999;font-size: 12px;}
  .file-tags{
    display: inline-block;
    background: #09ba79;
    color: #fff;
    padding: 4px 10px;margin-right: 10px;
    position: relative;
  }
  .file-tags a{
    display: block;width: 100%;height: 100%;
  }
  span.dele-file-icon, span.dele-img-icon{
    position: absolute;
    background: rgba(0,0,0,0.5);color: #fff;
    width: 18px;height: 18px;padding: 0;line-height: 18px;
    top: -8px;right: -8px;text-align: center;
    border-radius: 50%;
  }
  /*span.dele-file-icon.show-icon{visibility: visible;}*/
  .file-imgs{
    position: relative;
    display: inline-block;
    width: 120px;height: 80px;
    border-radius: 6px;border: 1px solid #eee;
    margin-bottom: 20px;margin-right: 10px;
  }
  .file-imgs img{display: block;width: 100%;height: 100%;}
</style>
